using System;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace LePcCtrlApp
{

    class LoginManager
    {
        private static readonly LoginManager instance = new LoginManager();
        private TcpClient tcp;
        byte[] buf;        
        private NetworkStream m_nsClient;
        private LoginManager()
        {
            buf = new byte[1024];           
        }

        public bool IsConnected()
        {
            return (tcp != null) && tcp.Connected;
        }

        public async Task<bool> Connect(string ip, int port)
        {
            if (tcp != null && tcp.Connected)
                tcp.Close();
            tcp = new TcpClient();
            try
            {
                await TimeoutHelper.Timeout(tcp.ConnectAsync(ip, port), 3000);
            }
            catch
            {
                return false;
            }
            if (tcp.Connected)
            {
                m_nsClient = tcp.GetStream();
                tcp.NoDelay = true;
            }
            return tcp.Connected;
        }

        public async Task<bool> Connect(string ip, string port)
        {
            return await Connect(ip, int.Parse(port));
        }

        public async Task<int> Receive()
        {
            Array.Clear(buf,0,buf.Length);
            return await TimeoutHelper.Timeout(m_nsClient.ReadAsync(buf, 0, 1024), 1000);            
        }

        public byte[] Buffer
        {
            get
            {
                return buf;
            }
        }

        public async void SendPacketAsync(byte[] data)
        {
            if (m_nsClient.CanWrite)
            {
                await TimeoutHelper.Timeout(m_nsClient.WriteAsync(data, 0, data.Length), 200);                     
            }
        }

        public void SendPacket(byte[] data)
        {
            if (m_nsClient.CanWrite)
            {
                m_nsClient.Write(data, 0, data.Length);
            }
        }

        public void Close()
        {
            if (tcp != null && tcp.Connected)
            {
                tcp.Close();
                m_nsClient.Close();
            }
        }

        public static LoginManager GetInstance()
        {
            return instance;
        }
    }

}